﻿using com.guojin.mj.net.message;
using com.guojin.mj.net.message.login;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using com.guojin.core.io.message;
using com.guojin.mj.net.message.club;
using com.guojin.mj.net.message.game;
using UnityEngine.UI;
using DG.Tweening;

public class GameController : MonoBehaviour
{
    private static GameController instance;
    public static GameController GetInstance()
    {
        return instance;
    }
    void Awake()
    {
        instance = this;
    }

    #region  //规则信息
    public const string chapterMax = "chapterMax";
    public const string middleJoin = "middleJoin";
    public const string betweenOnePointJvGuo = "betweenOnePointJvGuo";
    public const string cardCounts = "cardCounts";
    public const string scoreRange = "scoreRange";

    public void SaveRule(List<OptionEntry> options)
    {
        SaveOptionsToOptionDic(options);
        SaveRuleToPlayerPrefs();
    }

    private Dictionary<string, string> optionDic = new Dictionary<string, string>();
    private void SaveOptionsToOptionDic(List<OptionEntry> options)
    {
        optionDic.Clear();
        for (var i = 0; i < options.Count; i++)
            optionDic.Add(options[i].key, options[i].value);
    }

    private void SaveRuleToPlayerPrefs()
    {
        if (optionDic[chapterMax] == "16")
            PlayerPrefs.SetString(chapterMax, "16");
        else if (optionDic[chapterMax] == "32")
            PlayerPrefs.SetString(chapterMax, "32");

        if (optionDic[middleJoin] == "true")
            PlayerPrefs.SetString(middleJoin, "true");
        else if (optionDic[middleJoin] == "false")
            PlayerPrefs.SetString(middleJoin, "false");

        if (optionDic[betweenOnePointJvGuo] == "true")
            PlayerPrefs.SetString(betweenOnePointJvGuo, "true");
        else if (optionDic[betweenOnePointJvGuo] == "false")
            PlayerPrefs.SetString(betweenOnePointJvGuo, "false");

        PlayerPrefs.Save();
    }

    public string GetRuleFormPlayerPrefs(string str)
    {
        return PlayerPrefs.GetString(str);
    }
    #endregion

    // 玩家的位置信息
    public  int[] intArr = new int[8];         
    public void InitPlayerPosition()
    {
        int[] ARR0 = { 0, 1, 2, 3, 4, 5,};
        int[] ARR1 = { 5, 0, 1, 2, 3, 4,};
        int[] ARR2 = { 4, 5, 0, 1, 2, 3,};
        int[] ARR3 = { 3, 4, 5, 0, 1, 2,};
        int[] ARR4 = { 2, 3, 4, 5, 0, 1,};
        int[] ARR5 = { 1, 2, 3, 4, 5, 0,};

        switch (GameData.GetInstance().locationIndex)
        {
            case 0:
                intArr = ARR0;
                break;
            case 1:
                intArr = ARR1;
                break;
            case 2:
                intArr = ARR2;
                break;
            case 3:
                intArr = ARR3;
                break;
            case 4:
                intArr = ARR4;
                break;
            case 5:
                intArr = ARR5;
                break;
        }
    }

    //断线重连生成筹码
    public void InstantiateBet(string str)
    {
        if (string.IsNullOrEmpty(str))
            return;

        string[] betArr = str.Split(',');

            for (int i = 0; i < betArr.Length; i++)
            {
                if (!string.IsNullOrEmpty(betArr[i]))
                {
                GameController.GetInstance().InstantiateAddBetCircleAndDOTween(betArr[i], GameObject.Find("DeskBetPoint").transform);
                }    
            }
    }

    //检查是否所有玩家准备完成（显示开始按钮）
    public bool CheckAllReady()
    {
        bool allReady = true;
        foreach (var dic in GameRoomModel.GetInstance().playerDic)
        {
            if (dic.Value.IsReady || dic.Value.locationIndex == 0)
            {
                Debug.Log("玩家" + dic.Value.locationIndex + "已经准备");
            }
            else
            {
                allReady = false;
                Debug.Log("玩家" + dic.Value.locationIndex + "尚未准备，不能开始游戏");
            }
        }
        return allReady;
    }

    public void OnReceive122(string msg, Message data)
    {
        ReadyToStartTheGameRet pr = (ReadyToStartTheGameRet)data;

        //对应玩家准备，显示准备UI，动画消失
        GameRoomModel.GetInstance().playerDic[pr.LocationIndex].IsReady = true;

        //如过准备的人是自己,准备按钮变成灰色
        if (pr.LocationIndex == GameData.GetInstance().locationIndex)
            GameRoomPage.GetInstance().SetReadyBtn(0);

        //如果尚未开始游戏，遍历判断是否显示开始游戏
        if (GameRoomModel.GetInstance().RoomState == 0)
            GameRoomController.GetInstance().CheckReadyAndStartBtnState();
    }

    public void OnRecive123(string msg, Message data)
    {
        DealTheCardsRet gd = (DealTheCardsRet)data;

        if (gd.currentTurnNum == 1)
        {
            GameRoomController.GetInstance().StartGame();
        InitUI();
            Debug.Log("第一此发牌");
        }

        StartCoroutine(DealCard(gd));
    }

    void InitUI()
    {

        if(GameObject.Find("ChapterEndPage(Clone)"))//找到结算面板删除掉
        Destroy(GameObject.Find("ChapterEndPage(Clone)"));

        GameObject del = new GameObject("del");

        var loadPointGroup = GameObject.Find("loadPointGroup");
        if (loadPointGroup)
        {
            for (int i = 0; i < 6; i++)
            {
                Transform tran = loadPointGroup.transform.Find("player" + i + "/cardPoint/playerCard/cardGroup");
                if (tran)
                {
                    for (int j = 0; j < tran.childCount; j++)
                    {
                        tran.GetChild(j).SetParent(del.transform);
                    }
                }
            }
        }
        Destroy(del);
    }

    IEnumerator DealCard(DealTheCardsRet gd)//发牌动画
    {
        GameRoomPage.GetInstance().SetPanel(true);

        int temp = gd.currentTurnNum == 1 ? 3 : 1;

        for (int i = 0; i < temp; i++)
        {
            for (int j = gd.firstLocationIndex; j < GameRoomModel.GetInstance().MaxUser; j++)
            {
                int num = CheckUserCardsListContainsLocationIndex(gd.cardMsg, j);

                if (num != -1)
                {
                    if (gd.currentTurnNum == 1)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[i]); 
                    }
                    else if(gd.currentTurnNum == 2)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[3]);
                    }
                    else if(gd.currentTurnNum == 3)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[4]);                       
                    }
                    yield return new WaitForSeconds(0.1f);//原先是0.3改成0.1了
                }          
            }

            for (int j = 0; j < gd.firstLocationIndex; j++)
            {
                int num = CheckUserCardsListContainsLocationIndex(gd.cardMsg, j);

                if (num != -1)
                {
                    if (gd.currentTurnNum == 1)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[i]);
                    }
                    else if (gd.currentTurnNum == 2)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[3]);
                    }
                    else if (gd.currentTurnNum == 3)
                    {
                        GameRoomModel.GetInstance().playerDic[j].AddCard(gd.cardMsg[num].Cards[4]);                  
                    }
                    yield return new WaitForSeconds(0.1f);//原先是0.3改成0.1了发牌动画的速度变了
                }         
            }
        }

        DealEndShowCardType(gd);

        GameRoomPage.GetInstance().SetPanel(false);
    }

    private int  CheckUserCardsListContainsLocationIndex(List<UserHandCardsRet> userCardsList, int locationIndex)
    {
        int temp = -1;

        for (int i = 0; i < userCardsList.Count; i++)
        {
            if (userCardsList[i].LocationIndex == locationIndex)
            {
                return i;
            }   
        }
        return temp;
    }

    private void  DealEndShowCardType(DealTheCardsRet gd)
    {
        for (int i = 0; i < gd.cardMsg.Count; i++)
        {
            if (gd.cardMsg[i].Cards != null)
            {
                GameRoomModel.GetInstance().playerDic[gd.cardMsg[i].LocationIndex].AllCardType = gd.cardMsg[i].AllCardType;
                GameRoomModel.GetInstance().playerDic[gd.cardMsg[i].LocationIndex].ShowCardType = gd.cardMsg[i].ShowCardType;
                GameRoomModel.GetInstance().playerDic[gd.cardMsg[i].LocationIndex].ShowShowCardType();
                GameRoomModel.GetInstance().playerDic[gd.cardMsg[i].LocationIndex].InitBetState();
            }
        }
    }

    public void OnReceive128(string msg, Message data)
    {
        GameUserInfoRet gui = (GameUserInfoRet)data;

        if (GameRoomModel.GetInstance().playerDic.ContainsKey(gui.locationIndex))
        {
            GameRoomModel.GetInstance().playerDic[gui.locationIndex].Online = true;
        }
        else
        {
            //生成新的头像
            TooL.LoadPrefab(GameRoomPage.GetInstance().loadPointGroup[GameController.GetInstance().intArr[gui.locationIndex]].
                 gameObject.transform.FindChild("headPoint").gameObject, "playerHead");

            TooL.LoadPrefab(GameRoomPage.GetInstance().loadPointGroup[GameController.GetInstance().intArr[gui.locationIndex]].
              gameObject.transform.FindChild("cardPoint").gameObject, "playerCard");

            Player player = GameRoomPage.GetInstance().loadPointGroup[GameController.GetInstance().intArr[gui.locationIndex]].
                gameObject.transform.FindChild("headPoint/playerHead").gameObject.AddComponent<Player>();

            GameRoomModel.GetInstance().playerDic.Add(gui.locationIndex, player);

            player.InitPlayerUserInfo(gui);
        }

        if (GameRoomModel.GetInstance().RoomState == 0)
        {
            //遍历查看是否显示开始游戏
            GameRoomController.GetInstance().CheckReadyAndStartBtnState();
            //遍历查看是否灰色显示邀请好友
            GameRoomController.GetInstance().CheckInviteBtnState();
        }
    }


    public void OnReceiveMsg1213(string msg, Message data)
    {
        BetInfoRet bs = (BetInfoRet)data;
        CheckDeleteBetPage(bs.LocationIndex);
        ChangeUserState(bs.BetType, bs.LocationIndex);
        DeleteDownTimeAndSelect(bs.LocationIndex);
        BetOrCallAni(bs.LocationIndex, bs.BetOrCallScore);
        SyncSingleBetAndTotalBet(bs.BetType, bs.BetOrCallScore);     
    }

    private void CheckDeleteBetPage(int locationIndex)
    {
        if (locationIndex == GameData.GetInstance().locationIndex)
        {
            if (GameObject.Find("BetPage(Clone)"))
            {
                GameObject.Find("BetPage(Clone)").GetComponent<BetPage>().CloseBtnClick();
            }
        }
    }

    private void DeleteDownTimeAndSelect(int locationIndex)
    {
        GameRoomModel.GetInstance().playerDic[locationIndex].SetDownTime(false, 0);
        GameRoomModel.GetInstance().playerDic[locationIndex].IsSelect = false;
    }

    private void ChangeUserState(int betType, int locationIndex)
    {
        if (betType == 1)
        {
            GameRoomModel.GetInstance().playerDic[locationIndex].BetState = 2;
        }
        else if (betType == 2)
        {
            GameRoomModel.GetInstance().playerDic[locationIndex].BetState = 4;
            GameRoomModel.GetInstance().playerDic[locationIndex].PlayStateAni("跟注");
        }
        else if(betType == 3)
        {
            GameRoomModel.GetInstance().playerDic[locationIndex].BetState = 5;
            GameRoomModel.GetInstance().playerDic[locationIndex].PlayerState = 4;
            GameRoomModel.GetInstance().playerDic[locationIndex].isOut = true;
            GameRoomModel.GetInstance().playerDic[locationIndex].PlayStateAni("弃牌");
        }
    }

    private void BetOrCallAni(int locationIndex, int betOrCallScore)
    {
        if (betOrCallScore > 0)
        {
            if (betOrCallScore > GameRoomModel.GetInstance().MaxScore/2)
            {
                GameRoomPage.GetInstance().SetAudAndPlay(2);
            }
            else
            {
                GameRoomPage.GetInstance().SetAudAndPlay(1);
            }

            GameRoomModel.GetInstance().playerDic[locationIndex].PlayerBet(betOrCallScore);
        }      
    }

    private void SyncSingleBetAndTotalBet(int betType, int betOrCallScore)
    {
        if (betType == 1)
            GameRoomModel.GetInstance().AppendSingleBet(betOrCallScore);
    }


    public void OnReceive1215(string msg, Message data)         //0 取消托管  1开始托管
    {
        UserTrusteeshipRet uts = (UserTrusteeshipRet) data;

        if (GameObject.Find("GameRoomPage(Clone)"))
        {
            if (uts.trusteeshipState == 0)
            {
                GameRoomModel.GetInstance().playerDic[uts.locationIndex].IsTrusteeship = false;
            }
            else if (uts.trusteeshipState == 1)
            {
                GameRoomModel.GetInstance().playerDic[uts.locationIndex].IsTrusteeship = true;

                if (uts.locationIndex == GameData.GetInstance().locationIndex)
                {
                    UIManager.ChangeUI(UIManager.PageState.TrusteeShipPage, (GameObject obj) =>
                    {
                        obj.GetComponent<TruesteeShipPage>().InformationSetting();
                    });
                }
            }
        }
    }

    public void OnReceive1217(string msg, Message data)
    {
        TrusteeshipReadyRet tr = (TrusteeshipReadyRet) data;

        TrusteeshipReady1217(tr);

        //StartCoroutine(TrusteeshipReady(tr));
    }

    IEnumerator TrusteeshipReady(TrusteeshipReadyRet tr)//原先的是等待时间然后处理，现在修改为直接处理不再用协程
    {
        yield return new WaitForSeconds(6f);//修改了托管的等待时间。

        if (tr.ReadyLocationIndex == GameData.GetInstance().locationIndex)
        {
            if (GameObject.Find("ChapterEndPage(Clone)"))
            {
                GameObject.Find("ChapterEndPage(Clone)").GetComponent<ChapterEndPage>().CloseBtnClick();
            }

            GameRoomPage.GetInstance().SetReadyBtn(0);

            GameRoomController.GetInstance().ReadyBtnClickCallBack();
        }

        if (GameRoomModel.GetInstance().RoomState == 2)
        {
            GameRoomModel.GetInstance().playerDic[tr.ReadyLocationIndex].IsReady = true;
        }
    }

    //暂时不用自己写的方法逻辑有点问题
    private void TrusteeshipReady1217(TrusteeshipReadyRet tr)
    {
        //修改了托管的等待时间。

        if (tr.ReadyLocationIndex == GameData.GetInstance().locationIndex)
        {
            if (GameObject.Find("ChapterEndPage(Clone)"))
            {
                GameObject.Find("ChapterEndPage(Clone)").GetComponent<ChapterEndPage>().CloseBtnClick();
            }

            GameRoomPage.GetInstance().SetReadyBtn(0);

            GameRoomController.GetInstance().ReadyBtnClickCallBack();
        }

        if (GameRoomModel.GetInstance().RoomState == 2)
        {
            GameRoomModel.GetInstance().playerDic[tr.ReadyLocationIndex].IsReady = true;
        }
    }



    public void OnReceive1219(string msg, Message data)        //离线消息
    {
        UserOfflineRet uof = (UserOfflineRet)data;

        if (GameObject.Find("GameRoomPage(Clone)"))
        {
            GameRoomModel.GetInstance().playerDic[uof.locationIndex].Online = false;
            GameRoomModel.GetInstance().playerDic[uof.locationIndex].IsReady = false;

            if (GameRoomModel.GetInstance().RoomState == 0)
            {
                GameRoomController.GetInstance().CheckReadyAndStartBtnState();
            }
        }
    }

    #region //解散房间
    public void OnReceive1221(string msg, Message data)
    {
        VoteDissolveRoomRet uvr = (VoteDissolveRoomRet)data;

        //有人发起投票，将所有人的投过票改为false
        foreach (var dic in GameRoomModel.GetInstance().playerDic)
        {
            dic.Value.isVoteResult = false;
            dic.Value.VoteResult = false;
        }

        if (GameObject.Find("GameRoomPage(Clone)"))
        {
            GameData.GetInstance().voteUserId = uvr.userId.ToString();

            //收到玩家显示投票解散面板
            UIManager.ChangeUI(UIManager.PageState.VoteDissolveRoomPage , (GameObject obj) =>
            {
                obj.GetComponent<VoteDissolveRoomPage>().InformationSetting();
            });
        }
        else
        {
            Debug.Log("1221+没有找到战斗面板，这不是战斗场景");
        }
    }

    public void OnReceive1223(string msg, Message data)
    {
        VoteDissolveRoomResultRet uvrr = (VoteDissolveRoomResultRet)data;

        //将对应玩家投票设为已经投过票
        GameRoomModel.GetInstance().playerDic[uvrr.locationIndex].isVoteResult = true;
        GameRoomModel.GetInstance().playerDic[uvrr.locationIndex].VoteResult = uvrr.result;

        if (uvrr.locationIndex == GameData.GetInstance().locationIndex)
        {
            if (GameObject.Find("VoteDissolveRoomPage(Clone)"))
            {
                GameObject.Find("VoteDissolveRoomPage(Clone)").transform.FindChild("group").gameObject.SetActive(false);
            }
        }

        if (GameObject.Find("VoteDissolveRoomPage(Clone)"))
        {
            if (uvrr.result)
            {
                GameObject.Find("voteHead" + uvrr.locationIndex).transform.FindChild("value").GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/03/同意");
            }
            else
            {
                GameObject.Find("voteHead" + uvrr.locationIndex).transform.FindChild("value").GetComponent<Image>().sprite = Resources.Load<Sprite>("BDUI/03/拒绝");
                //GameObject.Find("VoteDissolveRoomPage(Clone)").GetComponent<VoteDissolveRoomPage>().ShowResultPanel(false, uvrr.locationIndex);     
                TooL.ShowNoticePage(GameRoomModel.GetInstance().playerDic[uvrr.locationIndex].userName+"玩家不同意解散房间");
                StartCoroutine(BoyDissolveRoom());
            }
        }
        else
        {
            Debug.Log("没有发现投票面板");
        }

        bool allVote = GetInstance().CheckAllVote();
        if (allVote)
        {
            bool allVoteResult = CheckAllVoteResult();
            if (allVoteResult)
            {
                GameObject.Find("VoteDissolveRoomPage(Clone)").GetComponent<VoteDissolveRoomPage>().ShowResultPanel(true, 0);
            }
        }
    }

    IEnumerator BoyDissolveRoom()
    {
        yield return new WaitForSeconds(0.5f);
        if (GameObject.Find("VoteDissolveRoomPage(Clone)"))
        {
            DestroyImmediate(GameObject.Find("VoteDissolveRoomPage(Clone)"));
        }
    }

    //是否所有玩家都发送过解散结果了
    public bool CheckAllVote()
    {
        bool IsVoteResult = true;
        foreach (var dic in GameRoomModel.GetInstance().playerDic)
        {
            if (dic.Value.isVoteResult)
            {
                Debug.Log("玩家" + dic.Value.locationIndex + "已经投票");
            }
            else
            {
                IsVoteResult = false;
                Debug.Log("玩家" + dic.Value.locationIndex + "尚未投票");
            }
        }
        return IsVoteResult;
    }

    //是否所有玩家都赞成解散
    public bool CheckAllVoteResult()
    {
        bool voteResult = true;
        foreach (var dic in GameRoomModel.GetInstance().playerDic)
        {
            if (dic.Value.VoteResult)
            {
                Debug.Log("玩家" + dic.Value.locationIndex + "投赞成票");
            }
            else
            {
                voteResult = false;
                Debug.Log("玩家" + dic.Value.locationIndex + "投拒绝票");
            }
        }
        return voteResult;
    }
    #endregion

    //循环删除各种战斗场景预设体
    public void DeleteAllExceptGameHall()
    {
        GameObject obj = GameObject.Find("Canvas/addNode");
        for (int i = 0; i < obj.transform.childCount;)
        {
            if (obj.transform.GetChild(i).name != "GameHallPage(Clone)")
            {
                Debug.Log("删除" + obj.transform.GetChild(i).name);
                UnityEngine.Object.DestroyImmediate(obj.transform.GetChild(i).gameObject);
            }
            else
            {
                i++;
            }
        }
    }

    //加注的动画
    //public void InstantiateAddBetCircleAndDOTween(string addScore, Transform PlayerPoint, float scale = 1.2f)
    //{
    //    GameObject obj = Resources.Load<GameObject>("SHPrefab/SHAddCircle" + addScore);
    //    if (obj != null)
    //    {
    //        obj = GameObject.Instantiate(obj);
    //        Debug.Log(obj);
    //        obj.transform.SetParent(GameObject.Find("DeskBetPoint").transform, false);
    //        obj.transform.localPosition = new Vector3(PlayerPoint.localPosition.x - 20, PlayerPoint.localPosition.y, PlayerPoint.localPosition.z);
    //        obj.transform.localScale = new Vector3(scale, scale, scale);
    //        obj.transform.name = addScore;
    //        obj.transform.DOLocalMove(UnityEngine.Random.insideUnitCircle * 100, 0.3f);
    //    }
    //}

    public void InstantiateAddBetCircleAndDOTween(string addScore, Transform PlayerPoint, float scale = 0.9f)
    {
        GameObject obj = Resources.Load<GameObject>("SHPrefab/AddCircle");
        if (obj != null)
        {
            obj = GameObject.Instantiate(obj);
            obj.GetComponent<AddCirclePage>().SetValue(addScore);
            obj.transform.SetParent(GameObject.Find("DeskBetPoint").transform, false);
            obj.transform.position = new Vector3(PlayerPoint.position.x - 20, PlayerPoint.position.y, PlayerPoint.position.z);
            obj.transform.localScale = new Vector3(scale, scale, scale);
            obj.transform.name = addScore;
            obj.transform.DOLocalMove(UnityEngine.Random.insideUnitCircle * 300, 0.3f);
        }
    }

    //图文字体的分数换算
    //public string transformScore(string  str)
    //{
    //    if (str.Substring(0, 1) == "-")
    //    {
    //        str = str.Replace("0", "A");
    //        str = str.Replace("1", "B");
    //        str = str.Replace("2", "C");
    //        str = str.Replace("3", "D");
    //        str = str.Replace("4", "E");
    //        str = str.Replace("5", "F");
    //        str = str.Replace("6", "G");
    //        str = str.Replace("7", "H");
    //        str = str.Replace("8", "I");
    //        str = str.Replace("9", "J");
    //    }
    //    else
    //    {
    //       str = "+" + str;
    //    }

    //    return str;
    //}
}
